package com.qf.service.Impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.mapper.BooksMapper;
import com.qf.pojo.Books;
import com.qf.service.IBooksService;
import com.fasterxml.jackson.core.type.TypeReference;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
@Service
public class BooksServiceImpl implements IBooksService {
    private BooksMapper booksMapper;
    private ObjectMapper objectMapper;
    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    private RestTemplate restTemplate;

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Autowired
    public void setBooksMapper(BooksMapper booksMapper) {
        this.booksMapper = booksMapper;
    }

    @Override
    public List<Books> findAll() throws JsonProcessingException {
//先去查询缓存,缓存中如果有数据,则直接返回,如果没有数据,查询数据库,并保存到缓存中
        String result = restTemplate.getForObject("http://localhost:11003/cache/get/allss", String.class);
        System.out.println("result"+result);
//      如果缓存中没有就去查询数据库
        if(result==null){
            System.out.println("来查询数据库了");
            List<Books> all = booksMapper.findAll();
//          保存到缓存中
            restTemplate.postForObject("http://localhost:11003/cache/set/allss", all, String.class);
            return all;
        }
        System.out.println("缓存中有数据");
//        缓存中有  将缓存中的JSON数据转换成 对象
        List<Books> booksList = objectMapper.readValue(result, new TypeReference<List<Books>>() {

        });
        return booksList;
    }
}
